package com.dcy.seatastorage.biz.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dcy.common.model.PageModel;
import com.dcy.db.base.service.BaseService;
import com.dcy.seatastorage.api.api.AStorageService;
import com.dcy.seatastorage.api.model.StorageTbl;
import com.dcy.seatastorage.biz.mapper.StorageTblMapper;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dcy
 * @since 2021-04-23
 */
@Slf4j
@DubboService(version = "1.0.0", timeout = 3000, interfaceClass = AStorageService.class)
public class StorageTblService extends BaseService<StorageTblMapper, StorageTbl> implements AStorageService {

    /**
     * 获取表格数据
     *
     * @param storageTbl
     * @return
     */
    public IPage<StorageTbl> pageListByEntity(StorageTbl storageTbl, PageModel pageModel) {
        LambdaQueryWrapper<StorageTbl> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StrUtil.isNotBlank(storageTbl.getCommodityCode()), StorageTbl::getCommodityCode, storageTbl.getCommodityCode());
        return super.page(pageModel, queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public boolean deduct(String commodityCode, int count) {
        log.info("当前 XID: {}", RootContext.getXID());
        //根据商品代码查询对象
        StorageTbl storageTbl = getOne(Wrappers.<StorageTbl>lambdaQuery().eq(StorageTbl::getCommodityCode, commodityCode));
        // 执行修改
        return update(new StorageTbl().setCount(storageTbl.getCount() - count),
                Wrappers.<StorageTbl>lambdaUpdate().eq(StorageTbl::getCommodityCode, commodityCode));
    }
}
